#include "file.h"

namespace base
{
namespace utils
{
bool File::saveTextTo(const std::string &file_name, const std::string &text)
{
  File file_to_write(file_name);
  if (file_to_write.open(std::ios::out | std::ios::app))
  {
    file_to_write.write(text);
    file_to_write.close();
    return true;
  }
  return false;
}
File::File(const std::string &file_name)
  : BaseFile(file_name)
{

}
std::size_t File::write(const std::string &content)
{

  auto before = file_stream_.tellp();
  file_stream_.write(content.data(), content.length());
  return file_stream_.tellp() - before;
}
std::string File::readAll(std::size_t offset)
{
  if (!file_stream_.is_open())
  {
    return "";
  }
  if (offset > 0)
  {
    seekInputPosition(offset);
  }
  std::stringstream buf;
  buf << file_stream_.rdbuf();
  return buf.str();
}
std::string File::read(std::size_t maxSize, std::size_t offset)
{
  if (!file_stream_.is_open())
  {
    return "";
  }
  if (offset > 0)
  {
    seekInputPosition(offset);
  }
  std::unique_ptr<char[]> buf(new(std::nothrow) char[maxSize + 1]);
  file_stream_.read(buf.get(), maxSize);
  std::size_t size = file_stream_.gcount();
  std::string str(buf.get(), size);
  return str;
}
std::string File::readLine(std::size_t maxSize, std::size_t offset)
{
  if (!file_stream_.is_open())
  {
    return "";
  }

  std::unique_ptr<char[]> buf(new(std::nothrow) char[maxSize + 1]);
  file_stream_.getline(buf.get(), maxSize);
  std::size_t size = file_stream_.gcount();
  std::string str(buf.get(), size);
  return str;
}

}
}
